import * as chalk from 'chalk';
import { Command } from 'commander';
import { ModelAppFactory } from "../../../app";
import { run } from '../../../main';
import { ICommand } from '../../interface';
import { ERROR_PREFIX } from '../../ui';
import { startCheckPath } from '../../utils';

interface IStartCommand {
  /**
   * @description 应用
   * @type {string}
   * @memberof IStartCommand
   */
  app: string;

  /**
   * @description 视图
   * @type {string}
   * @memberof IStartCommand
   */
  view: string;

  /**
   * @description 部件
   * @type {string}
   * @memberof IStartCommand
   */
  control: string;

  /**
   * @description 远程后台服务接口
   * @type {string}
   * @memberof IStartCommand
   */
  online: string;

  /**
   * @description 服务端口
   * @type {number}
   * @memberof IStartCommand
   */
  port: number;
}

export class StartCommand implements ICommand {
  /**
   * @description 加载命令
   * @param {Command} program
   * @memberof StartCommand
   */
  load(program: Command): void {
    program
      .command('start')
      .usage('<command> [options]')
      .option('-a, --app <app-path>', '预览应用')
      .option('-v, --view <view-path>', '预览视图')
      .option('-c, --control <control-path>', '预览部件')
      .option('-o, --online <online-host>', '启用远端后台服务')
      .option('-p, --port <port>', '以指定端口启动')
      .description('start preview service.')
      .action(this.action.bind(this))
  }

  /**
   * @description 执行行为
   * @param {IStartCommand} options
   * @memberof StartCommand
   */
  async action(options: IStartCommand) {
    if (!options.hasOwnProperty('app') && !options.hasOwnProperty('view') && !options.hasOwnProperty('control')) {
      console.error(`\n${ERROR_PREFIX} Start error: ${chalk.red('%s')}`, '启动预览服务必须指定模式');
      console.log(`See ${chalk.red('--help')} for a list of available commands.\n`);
      process.exit(1);
    }
    const appOptions: any = {};
    const modelAppFactory = ModelAppFactory.getInstance();
    let flag: boolean = true;
    if (options.app && startCheckPath('app', options.app)) {
      Object.assign(appOptions, { type: 'APP', path: options.app, port: options.port });
    } else if (options.view && startCheckPath('view', options.view)) {
      Object.assign(appOptions, { type: 'VIEW', path: options.view, port: options.port });
    } else if (options.control && startCheckPath('control', options.control)) {
      Object.assign(appOptions, { type: 'CONTROL', path: options.control, port: options.port });
    } else {
      flag = false;
    }
    if (!flag) {
      console.error(`\n${ERROR_PREFIX} Start error: ${chalk.red('%s')}`, '请输入正确的模型路径');
      console.log(`See ${chalk.red('--help')} for a list of available commands.\n`);
      process.exit(1);
    }
    if (options.online) {
      Object.assign(appOptions, {
        useLocalService: false,
        host: options.online
      });
    }
    modelAppFactory.init(appOptions);
    await run();
  }
}